﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Globalization;
using System.Text;
using System.Windows.Forms;
using ZoneFiveSoftware.Common.Visuals;
using ZoneFiveSoftware.Common.Data.Fitness;
using ZoneFiveSoftware.Common.Data.Measurement;
using STCommon.Controller;
using STCommon.Data;
using STCommon.Resources;
using DistributionPlugin.Controller;

namespace DistributionPlugin.View
{
    public partial class DistributionSetupControl : UserControl
    {
        public DistributionSetupControl()
        {
            InitializeComponent();

            CadenceRadioButton.Tag = Enums.SportTracksDataTrackTypes.Cadence;
            ElevationRadioButton.Tag = Enums.SportTracksDataTrackTypes.Elevation;
            GradeRadioButton.Tag = Enums.SportTracksDataTrackTypes.Grade;
            HeartRateRadioButton.Tag = Enums.SportTracksDataTrackTypes.HeartRate;
            SpeedRadioButton.Tag = Enums.SportTracksDataTrackTypes.Speed;
            PowerRadioButton.Tag = Enums.SportTracksDataTrackTypes.Power;
        }

        void OnOptionsInstance_OptionChanged(object sender, PropertyChangedEventArgs e)
        {
            RefreshControls();
        }

#region UI Callbacks

        private void HeartRateComboBox_Format(object sender, ListControlConvertEventArgs e)
        {
            HeartRate.PercentTypes unit = (HeartRate.PercentTypes)e.ListItem;

            switch (unit)
            {
                case HeartRate.PercentTypes.None:
                    {
                        e.Value = CommonResources.Text.LabelBPM;
                        break;
                    }
                case HeartRate.PercentTypes.PercentOfMax:
                    {
                        e.Value = CommonResources.Text.LabelPercentOfMax;
                        break;
                    }
                case HeartRate.PercentTypes.PercentOfReserve:
                    {
                        e.Value = CommonResources.Text.LabelPercentOfReserve;
                        break;
                    }
            }
        }

        private void FlowLayoutPanel_SizeChanged(object sender, EventArgs e)
        {
            // AutoSize doesn't work so well with a user control & the flow layout panel
            //  so we do it manually.  My handling of AutoSize might be the problem, I'm
            //  unsure.
            if (AutoSize)
            {
                this.Size = new Size(this.Size.Width, DataTypeFlowLayoutPanel.Height +
                                                      IntervalFlowLayoutPanel.Height);
                ConfigTableLayoutPanel.Size = this.Size;
            }
        }

        private void DataTypeRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton radioButtonChecked = sender as RadioButton;

            if (radioButtonChecked.Checked)
            {
                m_OptionsInstance.SelectedDataType = (Enums.SportTracksDataTrackTypes)radioButtonChecked.Tag;
            }
        }

        private void HeartRateComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            m_OptionsInstance.HeartRateReferential = (HeartRate.PercentTypes)HeartRateComboBox.SelectedItem;
        }

        private void IntervalValueTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            // Force validation change when pressing enter
            if (e.KeyCode == Keys.Enter)
            {
                SelectNextControl(IntervalValueTextBox, true, true, true, true);
                e.Handled = true;
            }
        }

        private void IntervalValueTextBox_Validating(object sender, CancelEventArgs e)
        {
            float minValue = 1;
            float maxValue = 9999;

            if (m_OptionsInstance.SelectedDataType == Enums.SportTracksDataTrackTypes.Grade)
            {
                minValue = 0.01f;
            }
            else if (m_OptionsInstance.SelectedDataType == Enums.SportTracksDataTrackTypes.Speed &&
                     m_LabelProvider.SpeedUnit == Speed.Units.Pace)
            {
                minValue = 0.01f;
            }

            if (m_OptionsInstance.SelectedDataType == Enums.SportTracksDataTrackTypes.HeartRate &&
                (m_OptionsInstance.HeartRateReferential == HeartRate.PercentTypes.PercentOfMax ||
                 m_OptionsInstance.HeartRateReferential == HeartRate.PercentTypes.PercentOfReserve))
            {
                maxValue = 100;
            }

            if (m_OptionsInstance.SelectedDataType == Enums.SportTracksDataTrackTypes.Speed &&
                m_LabelProvider.SpeedUnit == Speed.Units.Pace)
            {
                e.Cancel = !Utils.IsTextTimeInRange(IntervalValueTextBox.Text, minValue, maxValue);
            }
            else
            {
                e.Cancel = !Utils.IsTextFloatInRange(IntervalValueTextBox.Text, minValue, maxValue);
            }

            if (e.Cancel)
            {
                if (m_OptionsInstance.SelectedDataType == Enums.SportTracksDataTrackTypes.Speed &&
                    m_LabelProvider.SpeedUnit == Speed.Units.Pace)
                {
                    MessageBox.Show(String.Format(TextResourceManager.TimeRangeValidationText,
                                                  Utils.TimeMinutesToString(minValue),
                                                  Utils.TimeMinutesToString(maxValue)),
                                    TextResourceManager.ValueValidationTitleText,
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    MessageBox.Show(String.Format(TextResourceManager.DoubleRangeValidationText,
                                                  minValue, maxValue),
                                    TextResourceManager.ValueValidationTitleText,
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

                IntervalValueTextBox.Text = m_LabelProvider.GetIntervalTextForSelection();
            }
        }

        private void IntervalValueTextBox_Validated(object sender, EventArgs e)
        {
            if (m_OptionsInstance.SelectedDataType == Enums.SportTracksDataTrackTypes.Speed &&
                m_LabelProvider.SpeedUnit == Speed.Units.Pace)
            {
                m_OptionsInstance.SelectedDataTypeIntervalLength = Utils.TimeToFloatMinutes(IntervalValueTextBox.Text);
            }
            else
            {
                float parsedValue = float.Parse(IntervalValueTextBox.Text);

                m_OptionsInstance.SelectedDataTypeIntervalLength = parsedValue;
            }
        }

        private void ActiveLapsCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            Options.ActiveLapsOnly = ActiveLapsCheckBox.Checked;
        }

#endregion

        private void RefreshControls()
        {
            if (m_OptionsInstance != null)
            {
                CadenceRadioButton.Checked = m_OptionsInstance.SelectedDataType == (Enums.SportTracksDataTrackTypes)CadenceRadioButton.Tag;
                ElevationRadioButton.Checked = m_OptionsInstance.SelectedDataType == (Enums.SportTracksDataTrackTypes)ElevationRadioButton.Tag;
                GradeRadioButton.Checked = m_OptionsInstance.SelectedDataType == (Enums.SportTracksDataTrackTypes)GradeRadioButton.Tag;
                HeartRateRadioButton.Checked = m_OptionsInstance.SelectedDataType == (Enums.SportTracksDataTrackTypes)HeartRateRadioButton.Tag;
                SpeedRadioButton.Checked = m_OptionsInstance.SelectedDataType == (Enums.SportTracksDataTrackTypes)SpeedRadioButton.Tag;
                PowerRadioButton.Checked = m_OptionsInstance.SelectedDataType == (Enums.SportTracksDataTrackTypes)PowerRadioButton.Tag;

                HeartRateComboBox.Visible = HeartRateRadioButton.Checked;
                HeartRateComboBox.SelectedItem = m_OptionsInstance.HeartRateReferential;

                UnitsLabel.Visible = !HeartRateRadioButton.Checked;
                UnitsLabel.Text = m_LabelProvider.GetUnitsTextForSelection();
                IntervalValueTextBox.Text = m_LabelProvider.GetIntervalTextForSelection();

                CadenceRadioButton.Enabled = Utils.ActivitiesContainDataType(Activities, Enums.SportTracksDataTrackTypes.Cadence);
                ElevationRadioButton.Enabled = Utils.ActivitiesContainDataType(Activities, Enums.SportTracksDataTrackTypes.Elevation);
                GradeRadioButton.Enabled = Utils.ActivitiesContainDataType(Activities, Enums.SportTracksDataTrackTypes.Grade);
                HeartRateRadioButton.Enabled = Utils.ActivitiesContainDataType(Activities, Enums.SportTracksDataTrackTypes.HeartRate);
                SpeedRadioButton.Enabled = Utils.ActivitiesContainDataType(Activities, Enums.SportTracksDataTrackTypes.Speed);
                PowerRadioButton.Enabled = Utils.ActivitiesContainDataType(Activities, Enums.SportTracksDataTrackTypes.Power);

                ActiveLapsCheckBox.Checked = Options.ActiveLapsOnly;
            }
        }

        public void UICultureChanged(CultureInfo culture)
        {
            DataLabel.Text = CommonResources.Text.LabelData + ":";
            CadenceRadioButton.Text = CommonResources.Text.LabelCadence;
            ElevationRadioButton.Text = CommonResources.Text.LabelElevation;
            GradeRadioButton.Text = CommonResources.Text.LabelGrade;
            HeartRateRadioButton.Text = CommonResources.Text.LabelHeartRate;
            PowerRadioButton.Text = CommonResources.Text.LabelPower;
            SpeedRadioButton.Text = m_LabelProvider.GetSpeedLabelForSelection();

            HeartRateComboBox.Items.Clear();
            HeartRateComboBox.Items.Add(HeartRate.PercentTypes.None);
            HeartRateComboBox.Items.Add(HeartRate.PercentTypes.PercentOfMax);
            HeartRateComboBox.Items.Add(HeartRate.PercentTypes.PercentOfReserve);
            HeartRateComboBox.SelectedItem = m_OptionsInstance.HeartRateReferential;

            IntervalLabel.Text = PluginView.GetLocalizedString("IntervalText") + ":";
            UnitsLabel.Text = m_LabelProvider.GetUnitsTextForSelection();
            SpeedRadioButton.Text = m_LabelProvider.GetSpeedLabelForSelection();

            ActiveLapsCheckBox.Text = PluginView.GetLocalizedString("ActiveLapsOnlyText");
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public DistributionOptions Options
        {
            get { return m_OptionsInstance; }
            set
            {
                m_OptionsInstance = value;
                m_OptionsInstance.OptionChanged += new PropertyChangedEventHandler(OnOptionsInstance_OptionChanged);

                RefreshControls();
            }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public ILabelUnitProvider LabelProvider
        {
            set { m_LabelProvider = value; }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public IList<IActivity> Activities
        {
            get { return m_Activities; }
            set
            {
                m_Activities = value;

                RefreshControls();
            }
        }

        private DistributionOptions m_OptionsInstance = null;
        private ILabelUnitProvider m_LabelProvider = null;
        private IList<IActivity> m_Activities = null;
    }
}
